package com.my.note.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author lilun <a href="mailto:lil@chsi.com.cn">lilun</a>
 * @version $Id$ 2019年03月20 11:57
 */
public class MD5Util {

    static Log log = LogFactory.getLog(MD5Util.class.toString());

    public MD5Util() {
    }

    public static String MD5(String input) {
        byte[] defaultBytes = input.getBytes();
        MessageDigest algorithm = getDigest("MD5");
        algorithm.reset();
        algorithm.update(defaultBytes);
        byte[] messageDigest = algorithm.digest();
        StringBuffer hexString = new StringBuffer();

        for(int i = 0; i < messageDigest.length; ++i) {
            String hex = Integer.toHexString(255 & messageDigest[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }

            hexString.append(hex);
        }

        return hexString.toString();
    }


    public static MessageDigest getDigest(String algorithm) {
        MessageDigest digest = null;

        try {
            digest = MessageDigest.getInstance(algorithm);
            return digest;
        } catch (NoSuchAlgorithmException var3) {
            log.error("No " + algorithm + " available");
            return null;
        }
    }
}
